package com.ghh.app.monsterrush;

import java.util.List;
import java.util.Random;

public abstract class AbstractFactory<T> {
	private List<Weight>	weights;
	private int				total	= 0;
	private Random			random	= new Random();

	public AbstractFactory(List<Weight> weights) {
		this.weights = weights;
		for (Weight w : weights) {
			total += w.getWeight();
		}
	}

	public T create() {
		String name = getRandomName();
		return create(name);
	}

	private String getRandomName() {
		int r = random.nextInt(total) + 1;
		int v = 0;
		for (Weight w : weights) {
			v += w.getWeight();
			if (v >= r) {
				return w.getName();
			}
		}
		return null;	//never should be here
	}

	protected abstract T create(String name);

	protected static class Weight {
		private String	name;
		private int		weight;

		public Weight(String name, int weight) {
			this.name = name;
			this.weight = weight;
		}

		public String getName() {
			return name;
		}

		public int getWeight() {
			return weight;
		}
	}
}
